import 'package:flutter/material.dart';

class MyRouteObserver extends NavigatorObserver {
  List<Route> routeList = [];

  String get rootName => routeList.first.settings.name ?? "/";

  void replaceRoot(BuildContext context) {
    var last = routeList.last;
    routeList.toList().forEach((r) {
      if (r != last) {
        Navigator.removeRoute(context, r);
      }
    });
  }

  @override
  void didPush(Route route, Route previousRoute) {
    routeList.add(route);
    log("push", route, previousRoute);
  }

  @override
  void didReplace({Route<dynamic> newRoute, Route<dynamic> oldRoute}) {
    routeList.add(newRoute);
    routeList.remove(oldRoute);
    log("didReplace", newRoute, oldRoute);
  }

  @override
  void didRemove(Route<dynamic> route, Route<dynamic> previousRoute) {
    routeList.remove(route);
    log("didRemove", route, previousRoute);
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic> previousRoute) {
    routeList.remove(route);
    log("didPop", route, previousRoute);
  }

  var showLog = true;

  void log(String tag, Route<dynamic> route, Route<dynamic> pre) {
    if (!showLog) {
      return;
    }
    var name1 = route?.settings?.name;
    var name2 = pre?.settings?.name;
    print("$tag ${name1 ?? "null"} , pre = ${name2 ?? 'null'}");

    print("routeList = ${routeList.map((r) => r.settings.name).join(" , ")}");
  }
}
